DECLARE
    @segmentDocumentsXml XML
,   @documentsXml        XML
,   @returnXml           XML

DECLARE
    @DocumentCount int
,   @SegmentCount  int
,   @IndexTotal    int

SELECT
    @DocumentCount = (SELECT COUNT(*) FROM [Document])
,   @SegmentCount  = (SELECT COUNT(*) FROM Segment)

SET @IndexTotal = (@DocumentCount + @SegmentCount)

SET @segmentDocumentsXml = 
(
    SELECT
        SegmentDocument.SegmentId
    ,   SegmentDocument.DocumentId
    ,   Title                      = CAST('<![CDATA[' + ISNULL([Document].Title,'') + ']]>' AS xml)
    ,   DocumentShortName          = CAST('<![CDATA[' + ISNULL(DocumentShortName,'') + ']]>' AS xml)
    ,   FileName                   = CAST('<![CDATA[' + ISNULL(FileName,'') + ']]>' AS xml)
    ,   Path                       = CAST('<![CDATA[' + ISNULL(Path,'') + ']]>' AS xml)
    ,   Tag                        = CAST('<![CDATA[' + ISNULL(Tag,'') + ']]>' AS xml)
    ,   IsActive                   = ISNULL([Document].IsActive,0)
    ,   DocumentCount              = @DocumentCount
    ,   SegmentCount               = @SegmentCount
    ,   IndexTotal                 = @IndexTotal
    FROM
        SegmentDocument
    ,   [Document]
    WHERE
        SegmentDocument.DocumentId = [Document].DocumentId
    FOR XML AUTO, ELEMENTS, TYPE
)

SET @documentsXml = 
(

    SELECT
        SegmentId
    ,   DocumentId
    ,   Title             = CAST('<![CDATA[' + ISNULL(Title,'') + ']]>' AS xml)
    ,   DocumentShortName = CAST('<![CDATA[' + ISNULL(DocumentShortName,'') + ']]>' AS xml)
    ,   FileName          = CAST('<![CDATA[' + ISNULL(FileName,'') + ']]>' AS xml)
    ,   Path              = CAST('<![CDATA[' + ISNULL(Path,'') + ']]>' AS xml)
    ,   Tag               = CAST('<![CDATA[' + ISNULL(Tag,'') + ']]>' AS xml)
    ,   IsActive          = ISNULL(IsActive,0)
    ,   DocumentCount     = @DocumentCount
    ,   SegmentCount      = @SegmentCount
    ,   IndexTotal        = @IndexTotal
    FROM
        [Document] AS SegmentDocument
    FOR XML AUTO, ELEMENTS, TYPE
)

SET @returnXml = 
(
    SELECT
        @segmentDocumentsXml  "node()"
    ,   @documentsXml         "node()"
    FOR XML PATH('SegmentDocuments')
)

SELECT @returnXml